package com.xzb.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xzb.demo.utils.CertUtil;
import com.xzb.demo.utils.CryptoUtil;
import com.xzb.demo.utils.HttpUtil;
import com.xzb.demo.utils.RandomStringGenerator;
import com.xzb.demo.vo.RequestVO;
import com.xzb.demo.vo.payment.req.PaymentReqListVO;
import com.xzb.demo.vo.payment.req.PaymentReqVO;
import org.apache.commons.codec.binary.Base64;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;


/**
 * @author cuican
 * 灵工
 */
public class GatewayClientSample {

    public static String gatewayUrl = "https://taxpay.zhihuilg.com/api/";
//    public static String gatewayUrl = "http://127.0.0.1:8766/";

    // 平台公钥（用于加密 AESKey 和验签）
    public static String platform_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAipHwqr6EETu3qKDHUHFg40Oh+jLId+Zq12+b8M5kWx7BnCvaLEvwSvCK4galtO8D8REntfqU3UiCfeYTlMMV/QYWzcR8d7uPZkGraeu/rhqDzr3t5+Si228nCIYu43EzP3fI2PZX8kT/eI6FmZGGaV7U+I9CumGMasd9qjJJSFMxYLu1YeqhJPwG6jnYUvsMSkj8U/unNIgL03mzNY5F+/hT3LXfY5nHh7anuzOhGN35F1LLK1AUy62CLDBxsgEjMfw5acuk+9//2WJiQtXPiCTDspahrbihQmde57pcyWb/sA8Rq4kpH1zatlM9tU4zYwHT9molAvoaHyLJG16btQIDAQAB";

    // 商户私钥（用于签名 & 解密返回数据的 AESKey）
    public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJvNkwoBLDVmyokX55MIJvVWaY4v+RiTY1tJEUAYUiu2c4YoYZx5H/lj9x2Q2MlOCFW6kZTV6tam9AtBGqEdi/4Uwi0OVf/RT9m9zrLQGsZKV1JTSSZeRuzymZ01S0u8luM92LiGMDArZ2pEu2Pna5Y0HKcLUXqTVCBGM1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upa0lRXLQjfBmE7fCG3SLL1pz0DuJC7+ydO1LfFvHqS1l9ubdyv3gCLbwe1PQ+yQuQREywdN2nsjzeC9TNbLLrUat5bM1ctVEqmvRdGbwyhW+NXLjvMlHiqFPLZSklGt6sIbyj9Krm/bkZt65s6pQKBgAkqJzbzswfYCgLNEsuM/Q4gultrQf52mEZ+ZcqVMfRQXUeyJVa4Ih9KyXIH8Pv0PBHWsE5sqNSZMSfSf0Xzw959btgzbQdVzFruDwU1AtG4FaIUHribypdGfRjzYFDrwTclILuRbtiGv3ZDRcfbAcTiXhqj8i/CDPuPAAtAvhad";

    // 商户公钥（你手里有，用于后续开放验证，可以预留在这里）
    public static String merchant_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAybzZMKASw1ZsqJF+eTCCb1VmmOL/kYk2NbSRFAGFIrtnOGKGGceR/5Y/cdkNjJTghVupGU1erWpvQLQRqhHYv+FMItDlX/0U/Zvc6y0BrGSldSU0kmXkbs8pmdNUtLvJbjPdi4hjAwK2dqRLtj52uWNBynC1F6k1QgRjNVA4W4PMp1aM4gAcNIKZrQGPw1IN2SbTqH7V/20o/kb+c8MXSgwSRxM4vnt5saUKv8PTr15/yVJ7SEAV80iTIEDpzNFpsgOjW0zGEqJruaRQwn4uS5wqyyE4s1OG1E6GvmMjsWS1ym4BePoiCkuqKQq68JW7Q0K6gg6i7p9SRAvlwU7++QIDAQAB";

    public static final String merchantNo = "MI460985749859016704";

    /**
     * 调用支付接口
     */
    public static void main(String[] args) throws Exception {

        // 初始化证书（私钥/平台公钥）
        CertUtil.initPrivateKey(merchant_private_key);
        CertUtil.initPulbicKey(platform_public_key);

        // ====== 组装支付请求参数 ======
        PaymentReqVO paymentVO = new PaymentReqVO(
                String.valueOf(System.currentTimeMillis()),
                new BigDecimal("10000"), "潘海文", "6222032010019265110", "440903200006061514",
                "13682273695", "102602002118", "中国工商银行",
                "广东省", "广州市", "测试付款", "0", "0", "1");

        PaymentReqListVO paymentReqListVO = new PaymentReqListVO();
        paymentReqListVO.setBatchNo(String.valueOf(System.currentTimeMillis()));
        paymentReqListVO.setMerchantNo(merchantNo);
        paymentReqListVO.setTotalAmt(paymentVO.getPayAmount());
        paymentReqListVO.setChannelNo("5500");
        ArrayList<PaymentReqVO> payItems = new ArrayList<>();
        payItems.add(paymentVO);

        paymentReqListVO.setPayItems(payItems);
        paymentReqListVO.setTotalCount(payItems.size());

        // ====== 序列化请求体 ======
        String reqData = JSONObject.toJSONString(paymentReqListVO);

        // 生成 AES Key
        String aesKey = RandomStringGenerator.getRandomStringByLength(16);
        byte[] aesKeyBytes = aesKey.getBytes(StandardCharsets.UTF_8);

        // 加密请求体
        byte[] plainBytes = reqData.getBytes(StandardCharsets.UTF_8);
        String encryptData = new String(Base64.encodeBase64(
                CryptoUtil.AESEncrypt(plainBytes, aesKeyBytes, "AES",
                        "AES/ECB/PKCS5Padding", null)), StandardCharsets.UTF_8);

        // 商户私钥签名
        String sign = new String(Base64.encodeBase64(
                CryptoUtil.digitalSign(plainBytes, CertUtil.getPrivateKey(),
                        "SHA1WithRSA")), StandardCharsets.UTF_8);

        // AESKey 用平台公钥加密
        String encryptKey = new String(Base64.encodeBase64(
                CryptoUtil.RSAEncrypt(aesKeyBytes, CertUtil.getPublicKey(), 2048, 11,
                        "RSA/ECB/PKCS1Padding")), StandardCharsets.UTF_8);

        // ====== 组装最终请求对象 ======
        RequestVO requestVO = new RequestVO();
        requestVO.setMerchantNo(merchantNo);
        requestVO.setEncryptData(encryptData);
        requestVO.setEncryptKey(encryptKey);
        requestVO.setSign(sign);

        System.out.println("请求参数为：" + JSONObject.toJSONString(requestVO));

        // ====== 发起请求 ======
        String res = HttpUtil.doPost(gatewayUrl + "/settle/v1/pay",
                JSONObject.parseObject(JSONObject.toJSONString(requestVO)), "UTF-8");

        System.out.println("出款返回为: " + res);

        // ====== 解析响应 ======
        JSONObject resJson = JSON.parseObject(res);
        RequestVO resVO = JSON.parseObject(resJson.getString("data"), RequestVO.class);

        // ====== 解密返回数据 ======
        byte[] decodeBase64KeyBytes = Base64.decodeBase64(resVO.getEncryptKey().getBytes(StandardCharsets.UTF_8));
        byte[] aESKeyBytes = CryptoUtil.RSADecrypt(
                decodeBase64KeyBytes, CertUtil.getPrivateKey(), 2048, 11,
                "RSA/ECB/PKCS1Padding");

        byte[] decodeBase64DataBytes = Base64.decodeBase64(resVO.getEncryptData().getBytes(StandardCharsets.UTF_8));

        byte[] respDataBytes = CryptoUtil.AESDecrypt(decodeBase64DataBytes,
                aESKeyBytes, "AES", "AES/ECB/PKCS5Padding", null);

        // ====== 验签 ======
        byte[] signBytes = Base64.decodeBase64(resVO.getSign().getBytes(StandardCharsets.UTF_8));

        boolean isValid = CryptoUtil.verifyDigitalSign(respDataBytes, signBytes,
                CertUtil.getPublicKey(), "SHA1WithRSA");

        String resData = new String(respDataBytes, StandardCharsets.UTF_8);

        System.out.println("付款解密响应报文: " + resData);
        System.out.println("验签结果: " + isValid);

    }
}
